import 'package:flutter/foundation.dart';
import '../utils/api.dart';
import '../utils/logger.dart';

class PostListProvider with ChangeNotifier {
  final int _pageSize = 10;
  final List<Map<String, dynamic>> _posts = [];

  int _currentPage = 1;
  bool _isLoading = false;
  bool _hasMore = true;
  String sortBy = 'createdAt';
  String _searchKey = '';

  List<Map<String, dynamic>> get posts => List.unmodifiable(_posts);
  bool get isLoading => _isLoading;
  bool get hasMore => _hasMore;

  /// 获取某个帖子详情
  Map<String, dynamic>? getPostById(String postId) {
    return _posts.firstWhere(
          (p) => p['id'].toString() == postId,
      orElse: () => {},
    );
  }

  /// 更新 loading 状态并通知（仅当变化时）
  void _setLoading(bool loading) {
    if (_isLoading != loading) {
      _isLoading = loading;
      notifyListeners();
    }
  }

  /// 刷新状态（非重置请求时用）
  void _resetState() {
    _posts.clear();
    _currentPage = 1;
    _hasMore = true;
  }

  /// 拉取帖子列表（分页加载）
  Future<void> fetchPosts({bool reset = false}) async {
    if (_isLoading) return;

    if (reset) {
      _resetState();
      notifyListeners(); // 通知列表清空
    }

    _setLoading(true);

    try {
      final result = await Api.get(
        '/cms/post/page',
        params: {
          'current': '$_currentPage',
          'size': '$_pageSize',
          'sort': sortBy,
          'type': 'rent',
          'searchKey': _searchKey,
        },
      );

      final List<dynamic>? records = result['data']?['records'];
      final int total = result['data']?['total'] ?? 0;

      if (records != null && records.isNotEmpty) {
        final newPosts = records.map((e) {
          final post = Map<String, dynamic>.from(e);
          post['liked'] ??= false;
          post['likeCount'] ??= 0;
          return post;
        }).toList();

        _posts.addAll(newPosts);
      }

      _hasMore = _posts.length < total;
      _currentPage++;
    } catch (e, stack) {
      Log.e("获取帖子失败: $e\n$stack");
    } finally {
      _setLoading(false);
    }
  }

  /// 更新排序字段并重新加载数据
  void updateSort(String newSort) {
    if (sortBy != newSort) {
      sortBy = newSort;
      fetchPosts(reset: true);
    }
  }

  /// 搜索关键词变更
  void updateSearch(String keyword) {
    if (_searchKey != keyword) {
      _searchKey = keyword;
      fetchPosts(reset: true);
    }
  }

  /// 点赞 / 取消点赞
  Future<void> toggleLike(String postId, bool isCurrentlyLiked) async {
    final index = _posts.indexWhere((p) => p['id'].toString() == postId);
    if (index == -1) return;

    final post = _posts[index];
    final oldLiked = post['liked'] ?? false;
    final oldCount = post['likeCount'] ?? 0;

    // 乐观更新 UI
    _posts[index] = {
      ...post,
      'liked': !oldLiked,
      'likeCount': oldCount + (oldLiked ? -1 : 1),
    };
    notifyListeners();

    try {
      await Api.postForm(
        '/cms/post/like',
        params: {'postId': postId, 'like': (!isCurrentlyLiked) ? '1' : '0'},
      );
    } catch (e, stack) {
      Log.e("点赞失败: $e\n$stack");

      // 回滚
      _posts[index] = {
        ...post,
        'liked': oldLiked,
        'likeCount': oldCount,
      };
      notifyListeners();
    }
  }

  /// 手动刷新（调用者一般为 RefreshIndicator）
  Future<void> refreshPosts() async {
    await fetchPosts(reset: true);
  }
}
